
//
// 下载护理单元 2017/5/31
//
//



#import "DlPubDepartment.h"
#import "Networking.h"
#import "InitDbTable.h"
#import "UserDefault.h"
#import <TMCache.h>
#import "HBaseViewController.h"

@implementation DlPubDepartment

-(instancetype)init{
    
    NSString *url = AppServiceConfig.GetServiceUrl;
    self.downloadUrl  = [NSString stringWithFormat:@"%@/%@?userid=%@&token=%@",url,@"getdepartment",UserDefault.getUserInfo.USER_ID,[[TMCache sharedCache] objectForKey:@"deviceToken"]];
    return self;
}

-(void) startDownload:(void(^)())callback{
    NSLog(@"开始 下载护理单元");
     
    [Networking receiveDataWithURLString:self.downloadUrl method:@"GET" body:nil Block:^(NSData *tempData) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:tempData options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *arr = [[NSMutableArray alloc]init];
        InitDbTable* initdb = [[InitDbTable alloc]init];
        
        HBaseViewController *basev = [[HBaseViewController alloc]init];
        
        Boolean flag =  [[dic valueForKey:@"flag"] boolValue];
        NSString *msg = (NSString*)[dic objectForKey: @"msg" ];
        
        if(! flag ){
            
            [basev alert:msg];
            return;
        }
        
        NSDictionary *data = [dic objectForKey: @"data" ];
        NSLog(@"下载成功，共%lu条护理单元数据",(unsigned long)[data count]);
        
        for (NSDictionary *diction in data) {
            Model_Pub_Department_Nurse *model =[[Model_Pub_Department_Nurse alloc]initWithDictionary:diction];
            [arr addObject:model];
        }
        
        NSLog(@"正在清除原有护理单元数据");
        [initdb deletePubDepartment];
        
        NSLog(@"正在写入护理单元数据");
        [initdb insertPubDepartmentArray:arr];
        
        if(callback){
            callback();
        }
        
        NSLog(@"完成 下载护理单元");
        
    }];
    
}


@end
